/*
  前端开发：李利强
  功能组件：待办中心
*/
import React, { useEffect, useState } from 'react';
import { Col, Row, Segmented, Typography, Button, Select, Input, DatePicker, Table, Tag, Pagination } from "antd";
import { SearchOutlined, ArrowLeftOutlined, ArrowRightOutlined } from '@ant-design/icons';
import type { DatePickerProps, PaginationProps } from 'antd';
import chongIcon from "../../img/chongIcon.svg";
import shuaIcon from "../../img/shuaIcon.svg";
import shaiIcon from "../../img/shaiIcon.svg";
import shaiIcon2 from "../../img/shaiIcon2.svg";

// import { GetTodoList } from "../../api/otherSystem.ts";

import "./TodoList.less";
const { Link } = Typography;

type AlignType = 'left' | 'right' | 'center';

// interface tabType {
//   label: string;
//   value: string;
// }

interface PrimaryData {
  key: string; //（key或者id）
  name: string; // 计划接收
  version: string; //版本
  date: string; //时间
  remainder: number; //剩余天数
  status: string; //状态
  sysId: string;
  taskList?: SecondaryData[];
}

interface SecondaryData {
  key: string; //（key或者id）
  name: string; // 名称
  stagingDate: string; // 暂存时间
  rejectDate: string; // 驳回时间
  initiateDate: string; //发起时间
  endDate: string; // 结束时间
  deadline: string; // 截止日期
  submitDate: string; // 提交时间
  reachDate: string; // 到达时间
  rejectedBy: string; // 驳回人
  endBy: string; // 结束人
  processedBy: string; // 处理人
  promoter: string; // 发起人
  reason: string; // 原因
  status: string; // 状态
}

interface TypeCount {
  pending: number; // 待办
  mybill: number; // 草稿
  processed: number; // 已办
  history: number; // 已办结
}

const TodoCenter: React.FC = () => {

  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [isScreen, setScreen] = useState<boolean>(false);
  const [todoDataList, setTodoDataList] = useState<any[]>([]);
  const [total, setTotal] = useState<number>(88);
  const [pageNo, setPageNo] = useState<number>(1);
  const [taskType, setTaskType] = useState<string>('pending');
  const [userName, setUserName] = useState<string>('9999');
  const [userId, setUserId] = useState<string>('9999');
  const [startTime, setStartTime] = useState<string | string[]>('2024-6-6 10:12:33');
  const [endTime, setEndTime] = useState<string | string[]>('2024-7-7 10:12:33');
  const [updateTime, setUpdateTime] = useState<string>('');
  const [tabOptions, setTabOptions] = useState<any[]>([])
  // setTabOptions
  const [sysId, setSysId] = useState<string>('1')

  useEffect(() => {
    getTodoData();
    if (!isUpdate) {
      getTime()
    }

  }, [pageNo, taskType, sysId]);

  // 列表接口
  const getTodoData = async () => {

    const param = JSON.stringify({
      userName: userName,
      userId: userId,
      timestamp: 1717405554620,
      sysId: sysId,
      bizParam: {
        isPaging: 1,
        endTime: startTime,
        startTime: endTime,
        filterLastTask: "1",
        loadStartTask: "0",
        pageNo: pageNo,
        pageSize: 100,
        taskType: taskType
      }
    });

    console.log(param);
    setTabOptions([{
      label: `待办(0})`,
      value: 'pending'
    }, {
      label: `已办(0)`,
      value: 'processed'
    }, {
      label: `已办结(0)`,
      value: 'history'
    }, {
      label: `草稿(0)`,
      value: 'mybill'
    }])


    //  await GetTodoList(param).then((res: any) => {
    //       if (res.data) {
    //         setTodoDataList(res.data)
    //         setTotal(res.total)
    //         const typeObj = res.data[0].typeCount as TypeCount

    //         const tab = [
    //           {
    //             label: `待办(${typeObj.pending})`,
    //             value: 'pending'
    //           }, {
    //             label: `已办(${typeObj.processed})`,
    //             value: 'processed'
    //           }, {
    //             label: `已办结(${typeObj.history})`,
    //             value: 'history'
    //           }, {
    //             label: `草稿(${typeObj.mybill})`,
    //             value: 'mybill'
    //           }]
    //         setTabOptions(tab)
    //       }
    //     });

    setTimeout(() => {
      let res = {
        code: 200,
        msg: "Success",
        data: [
          {
            key: "3E82850A393E484A9DFA8AF7B6DECF3B",
            name: "月度预算流程",
            version: "V1",
            date: "2024",
            remainder: 0,
            status: "mybill",
            sysId: "BUDGET",
            totalCount: 88,
            totalPage: 1,
            typeCount: { mybill: 2, pending: 1, processed: 4, history: 8 },
            taskList: [
              {
                reason: "描述不符合",
                endDate: "",
                submitDate: "",
                stagingDate: "2024-02-29 15:37:55",
                endBy: "",
                rejectedBy: "李鹅鹅",
                rejectDate: "",
                reachDate: "",
                name: "编制",
                initiateDate: "2024-02-29 15:37:55",
                promoter: "发起人名称",
                deadline: "",
                processedBy: "处理人",
                key: "S_1",
                status: "mybill"
              }
            ]
          },
          {
            key: "3E82850A393E484A9DFA8AF7B6DECF32",
            name: "月度预算流程2",
            version: "V2",
            date: "2024",
            remainder: 0,
            status: "pending",
            sysId: "TAX",
            totalCount: 1,
            totalPage: 1,
            taskList: [
              {
                reason: "",
                endDate: "",
                submitDate: "",
                stagingDate: "",
                endBy: "",
                rejectedBy: "",
                rejectDate: "",
                reachDate: "2024-03-29 15:37:55",
                name: "编制2",
                initiateDate: "2024-02-29 15:37:55",
                promoter: "发起人名称2",
                deadline: "2024-03-29 15:37:55",
                processedBy: "处理人2",
                key: "S_2",
                status: "pending"
              },
              {
                reason: "",
                endDate: "",
                submitDate: "",
                stagingDate: "",
                endBy: "",
                rejectedBy: "",
                rejectDate: "",
                reachDate: "",
                name: "编制3",
                initiateDate: "2024-02-29 15:37:55",
                promoter: "发起人名称3",
                deadline: "",
                processedBy: "处理人3",
                key: "S_3",
                status: "pending"
              }
            ]
          },
          {
            key: "3E82850A393E484A9DFA8AF7B6DECF30",
            name: "月度预算流程3",
            version: "V3",
            date: "2024",
            remainder: 0,
            status: "processed",
            sysId: "FXYJ",
            totalCount: 1,
            totalPage: 1,
            taskList: [
              {
                reason: "",
                endDate: "",
                submitDate: "2024-03-29 15:37:55",
                stagingDate: "",
                endBy: "",
                rejectedBy: "",
                rejectDate: "",
                reachDate: "",
                name: "编制3",
                initiateDate: "2024-02-29 15:37:55",
                promoter: "发起人名称3",
                deadline: "2024-02-29 15:37:55",
                processedBy: "处理人3",
                key: "S_3",
                status: "processed"
              }
            ]
          },
          {
            key: "3E82850A393E484A9DFA8AF7B6DECF34",
            name: "月度预算流程4",
            version: "V4",
            date: "2024",
            remainder: 0,
            status: "history",
            sysId: "FXYJ",
            totalCount: 1,
            totalPage: 1,
            taskList: [
              {
                reason: "",
                endDate: "2024-03-29 15:37:55",
                submitDate: "",
                stagingDate: "",
                endBy: "结束人",
                rejectedBy: "",
                rejectDate: "",
                reachDate: "",
                name: "编制4",
                initiateDate: "2024-02-29 15:37:55",
                promoter: "发起人名称4",
                deadline: "",
                processedBy: "处理人4",
                key: "S_4",
                status: "history"
              }
            ]
          }
        ]
      };
      setTodoDataList(res.data);
      if (res.data.length > 0) {
        const typeObj = res.data[0].typeCount as TypeCount;
        setTotal(res.data[0]?.totalCount);

        const tab = [
          {
            label: `待办(${typeObj.pending})`,
            value: "pending"
          },
          {
            label: `已办(${typeObj.processed})`,
            value: "processed"
          },
          {
            label: `已办结(${typeObj.history})`,
            value: "history"
          },
          {
            label: `草稿(${typeObj.mybill})`,
            value: "mybill"
          }
        ];
        setTabOptions(tab);
      }
      console.log(todoDataList);
    }, 1000);
  };

  const getTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    const seconds = String(now.getSeconds()).padStart(2, "0");
    const time = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
    setUpdateTime(time);
    setIsUpdate(true);
    // console.log(`${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`);
  };

  const onUpdate = () => {
    window.location.reload()
  }

  const sysClick = (value: string) => {
    console.log(value);
    setSysId(value);
  };
  // 过滤系统logo
  const sysIdFlr = (sysId: string) => {
    let dom: React.ReactNode = <span className="shui-icon">无</span>;
    switch (sysId) {
      case "TAX":
        dom = <span className="shui-icon">税</span>;
        break;
      case "BUDGET":
        dom = <span className="shui-icon gu-icon">股</span>;
        break;
      case "FXYJ":
        dom = <span className="shui-icon xian-icon">险</span>;
        break;
      default:
        // 默认处理逻辑，如果有需要的话
        break;
    }
    return dom;
  };

  // 过滤不同状态下的时间显示
  const timeFlr = (record: SecondaryData) => {
    let time: React.ReactNode = (
      <span>
        <Tag className="staging-tag">暂存</Tag> {record.stagingDate}
      </span>
    );
    switch (record.status) {
      case "mybill":
        time = (
          <span>
            {record.stagingDate === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag">暂存</Tag> {record.stagingDate}
              </span>
            )}
            {record.rejectDate === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag color="#FF3B00" style={{ marginLeft: 26 }}>
                  驳回
                </Tag>{" "}
                {record.rejectDate}
              </span>
            )}
            {record.deadline === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag color="warning" style={{ marginLeft: 26 }}>
                  截止
                </Tag>{" "}
                {record.deadline}
              </span>
            )}
          </span>
        );
        break;
      case 'pending':
        time = <span>
          {record.initiateDate === '' ? <span></span> : <span><Tag className='staging-tag'>发起</Tag> {record.initiateDate}</span>}
          {record.reachDate === '' ? <span></span> : <span><Tag className='staging-tag' style={{ marginLeft: 26 }}>到达</Tag> {record.reachDate}</span>}
          {record.deadline === '' ? <span></span> : <span><Tag color='warning' style={{ marginLeft: 26 }}>截止</Tag> {record.deadline}</span>}
        </span>
        break;
      case 'processed':
        time = <span>
          {record.initiateDate === '' ? <span></span> : <span><Tag className='staging-tag'>发起</Tag> {record.initiateDate}</span>}
          {record.submitDate === '' ? <span></span> : <span><Tag className='staging-tag' style={{ marginLeft: 26 }}>提交</Tag> {record.submitDate}</span>}
          {record.deadline === '' ? <span></span> : <span><Tag color='warning' style={{ marginLeft: 26 }}>截止</Tag> {record.deadline}</span>}
        </span>
        break;
      case "history":
        time = (
          <span>
            {record.initiateDate === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag">发起</Tag> {record.initiateDate}
              </span>
            )}
            {record.endDate === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag" style={{ marginLeft: 26 }}>
                  结束
                </Tag>{" "}
                {record.endDate}
              </span>
            )}
          </span>
        );
        break;
      default:
        // 默认处理逻辑，如果有需要的话
        break;
    }

    return time;
  };

  // 过滤不同状态下操作人员显示
  const promoterFlr = (record: SecondaryData) => {
    let person: React.ReactNode = (
      <span>
        <Tag className="staging-tag">暂存</Tag> {record.stagingDate}
      </span>
    );
    switch (record.status) {
      case "mybill":
        person = (
          <span>
            {record.rejectedBy === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag">驳回人</Tag> {record.rejectedBy}
              </span>
            )}
            {record.reason === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag" style={{ marginLeft: 26 }}>
                  原因
                </Tag>{" "}
                {record.reason}
              </span>
            )}
          </span>
        );
        break;
      case "pending":
        person = (
          <span>
            {record.processedBy === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag">处理人</Tag> {record.processedBy}
              </span>
            )}
            {record.promoter === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag" style={{ marginLeft: 26 }}>
                  发起人
                </Tag>{" "}
                {record.promoter}
              </span>
            )}
          </span>
        );
        break;
      case 'processed':
        person = <span>
          {record.processedBy === '' ? <span></span> : <span><Tag className='staging-tag'>处理人</Tag> {record.processedBy}</span>}
          {record.promoter === '' ? <span></span> : <span><Tag className='staging-tag' style={{ marginLeft: 26 }}>发起人</Tag> {record.promoter}</span>}
        </span>
        break;
      case "history":
        person = (
          <span>
            {record.endBy === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag">结束人</Tag> {record.endBy}
              </span>
            )}
            {record.promoter === "" ? (
              <span></span>
            ) : (
              <span>
                <Tag className="staging-tag" style={{ marginLeft: 26 }}>
                  发起人
                </Tag>{" "}
                {record.promoter}
              </span>
            )}
          </span>
        );
        break;
      default:
        // 默认处理逻辑，如果有需要的话
        break;
    }

    return person;
  }

  const columnsList = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      render: (_text: string, record: PrimaryData) => (
        <span>
          {sysIdFlr(record.sysId)}
          {record.name}
        </span>
      ),
      width: "19%"
    },
    {
      title: "version",
      dataIndex: "versionDate",
      render: (_text: string, record: PrimaryData) => (
        <span style={{ paddingLeft: "5px" }}>
          <span className="version-bg">版本：{record.version}</span>
          <span className="version-bg">时间：{record.date} 年</span>
        </span>
      ),
      width: "44%"
    },
    {
      title: "remainder",
      dataIndex: "remainder",
      key: "remainder",
      render: (_text: string, record: PrimaryData) => <span className="version-bg yellow-bg"> 还剩 {record.remainder} 天</span>,
      width: "19%"
    },
    {
      title: "button",
      dataIndex: "button",
      // render: (_text: string, record: PrimaryData) => (
      render: (_text: string) => <Link underline>立即查看</Link>,
      width: "15%",
      align: "right" as AlignType
    }
  ];

  const childrenColumns = [
    {
      title: 'name',
      dataIndex: 'name',
      key: 'name',
      width: '20%'
    },
    {
      title: "startDate",
      dataIndex: "startEnd",
      render: (_text: string, record: SecondaryData) => <span>{timeFlr(record)}</span>,
      width: "45%"
    },
    {
      title: 'promoter',
      dataIndex: 'promoterEndBy',
      render: (_text: string, record: SecondaryData) => (
        <span>
          {promoterFlr(record)}
        </span>
      ),
      width: '20%'
    },
    {
      title: 'button',
      dataIndex: 'button',
      // render: (_text: string, record: PrimaryData) => (
      render: (_text: string) => (
        <span>
          {/* <a style={{ marginRight: 20 }}>去提交</a> */}
          <Link underline>立即导入</Link>
          <Link underline>去办理</Link>
          <Link underline>流程节点</Link>
        </span>
      ),
      width: '15%',
      align: 'right' as AlignType
    }
  ]

  // 分页配置项
  const itemRender: PaginationProps['itemRender'] = (_, type, originalElement) => {
    if (type === 'prev') {
      return <Button type="link" icon={<ArrowLeftOutlined />}> 上一页 </Button>;
    }
    if (type === 'next') {
      return <Button type="link" icon={<ArrowRightOutlined />} iconPosition="end"> 下一页 </Button>;
    }
    return originalElement;
  };

  const btnList = [
    { id: '1', name: '全部' },
    { id: '2', name: '数据分析' },
    { id: '3', name: '预算' },
    { id: '4', name: '报表' },
    { id: '5', name: '资金' },
    { id: '6', name: '税务' },
    { id: '7', name: '股权' },
    { id: '8', name: '保险' },
    { id: '9', name: '综合管理' },
    { id: '10', name: '信用风险' },
    { id: '11', name: '金融衍生' }
  ]

  const businessList = [
    { value: '1', label: '暂无数据' },
  ]

  const tabChange = (value: string) => {
    console.log(value);
    setTaskType(value)
  }

  const nameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value;
    console.log(newValue);
    setUserName(newValue)
  }

  const onReset = () => {
    setUserName('')
    setUserId('')
    setStartTime('')
    setEndTime('')
    // setTaskType('pending')
  }

  const pageChange = (page: number) => {
    setPageNo(page)
  }

  const businessChange = (value: string) => {
    console.log(value);
    setUserId(value)
  }

  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  }

  const startTimeChange: DatePickerProps['onChange'] = (date, dateString) => {
    console.log(date, dateString);
    setStartTime(dateString)
  };

  const endTimeChange: DatePickerProps['onChange'] = (date, dateString) => {
    console.log(date, dateString);
    setEndTime(dateString)
  };

  const screenClick = () => {
    setScreen(!isScreen)
  }

  // 子列表
  const expandedRowRender = (record: PrimaryData) => (
    <Table
      dataSource={record.taskList || []}
      columns={childrenColumns}
      pagination={false}
      showHeader={false}
      size="small"
    />
  );

  return (
    <div className="todo-center">
      {/* 顶部 */}
      <Row className='todo-top'>
        {/* <Col span={2}>
          <div className='todo-top-title'>
            <span className='hexagon'></span>
            待办中心
          </div>
        </Col> */}
        <Col span={18}>
          <div>
            <span className='todo-top-title'>
              <span className='hexagon'></span>
              待办中心
            </span>
            <Segmented
              style={{ marginBottom: 8, height: 30, borderRadius: 15, marginLeft: 49 }}
              onChange={tabChange}
              options={tabOptions}
              defaultValue={taskType}
            />
          </div>
        </Col>
        <Col span={6}>
          <div className='todo-top-time'>
            <span>更新时间：{updateTime}</span>
            <Button size="small" onClick={onUpdate} style={{ marginLeft: 15, marginRight: 26, color: '#707070' }}> <img src={shuaIcon} alt="" /><span style={{ marginRight: 3 }}>刷新</span> </Button>
          </div>
        </Col>
      </Row>
      {/* 搜索条件 */}
      <Row className='todo-sreach'>
        <Col span={15} className='btn-list'>
          {
            btnList.map((item, index) => (
              <Button type={sysId === item.id ? 'primary' : 'default'} key={index} onClick={() => sysClick(item.id)}>{item.name}</Button>
            ))
          }
        </Col>
        <Col span={9}>
          <div className='sreach-set'>
            <Select
              // defaultValue={userId}
              style={{ width: 160, height: 28 }}
              onChange={handleChange}
              options={businessList}
              placeholder="业务类型"
            />
            <Input onChange={nameChange} style={{ width: 160, height: 28, marginLeft: 10 }} placeholder="请输入标题或编号" />
            <Button type="primary" style={{ backgroundColor: '#63B0FF' }} onClick={getTodoData} icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={onReset}>
              <img src={chongIcon} alt="" />
              重置
            </Button>
            <Button type={isScreen ? 'primary' : 'default'} onClick={screenClick} ghost>
              {isScreen ? <img src={shaiIcon2} alt="" /> : <img src={shaiIcon} alt="" />}
              {isScreen ? '收起筛选' : '高级筛选'}
            </Button>
          </div>
        </Col>
      </Row>
      {/* 高级筛选 */}
      {
        isScreen &&
        <div className='screen'>
          <DatePicker className='size-sty' onChange={startTimeChange} placeholder='请选择开始日期' />
          <DatePicker className='size-sty' onChange={endTimeChange} placeholder='请选择结束日期' />
          <Select
            className='size-sty'
            // defaultValue={userId}
            onChange={handleChange}
            options={businessList}
            placeholder="请输入或选择纳税主体"
          />
          <Select
            className='size-sty'
            // defaultValue={userId}
            onChange={businessChange}
            options={businessList}
            placeholder="处理人"
          />
          <Select
            className='size-sty'
            // defaultValue={userId}
            onChange={handleChange}
            options={businessList}
            placeholder="发起人"
          />
          <Select
            className='size-sty'
            // defaultValue={userId}
            onChange={handleChange}
            options={businessList}
            placeholder="选择任务属期"
          />
        </div>
      }
      {/* 待办列表 */}
      <div className='todo-list'>
        <Table
          dataSource={todoDataList}
          columns={columnsList}
          expandable={{
            expandedRowRender,
            // rowExpandable: (record) => !!secondaryDataSource[record.key],
          }}
          showHeader={false}
          pagination={false}
          size="middle"
          rowClassName="expanded-row-background"
        />
        {/* 分页 */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Pagination total={total} onChange={pageChange} itemRender={itemRender} />
        </div>
      </div>
    </div>
  );
};

export default TodoCenter;
